<template>
  <main-card-admin title="学生与班级" :loading="globalLoading" :show-screen-space="false" :main-body-style-obj="{ paddingTop: '12px' }">
    <template #tool-btn>
      <div class="flex gap-x-8">
        <a-button @click="openInviteModal">邀请</a-button>
        <a-button @click="openJoinAuditModal">
          <a-badge dot :offset="[4, -4]">审核</a-badge>
        </a-button>
        <a-button @click="openImportModal">导入</a-button>
        <a-button v-auth="'admin-students-and-classes-manage'" type="primary" @click="openStudentsForm">新增学生</a-button>
      </div>
    </template>
    <div class="content-wrap">
      <staff-constitute v-model:selected-keys="selectedKeys" @treeSelect="treeSelect" />
      <div class="table-wrap">
        <div class="flex mb-20">
          <a-input
            v-model:value="pageForm.name"
            v-trim
            class="w-328px"
            placeholder="学生姓名、学号"
            @keyup.enter="getDataList({ offset: 1 })"
          >
            <template #prefix> <i class="iconfont icon-search-line"></i> </template>
          </a-input>
          <a-button v-auth="'admin-students-and-classes-manage'" class="ml-auto" @click="() => (batchDisposeVisible = !batchDisposeVisible)"
            >批量操作</a-button
          >
        </div>
        <GTable
          :action-width="60"
          :columns="columns"
          :data="dataList"
          :page-form="pageForm"
          :loading="loading"
          row-key="id"
          :action-option="actionOption"
          :row-selection="rowSelection"
          @getDataList="getDataList"
        />
      </div>
    </div>
  </main-card-admin>
  <g-batch-dispose v-model:data-list="rowSelection.selectedRowKeys" :total="pageForm.total" :visible="batchDisposeVisible">
    <a-button
      v-auth="'admin-students-and-classes-manage'"
      :disabled="!rowSelection.selectedRowKeys.length"
      :loading="batchDeleteLoading"
      @click="batchDeletionOfIDs"
      >批量删除</a-button
    >
  </g-batch-dispose>

  <students-form ref="studentsFormRef" @submit="studentsFormSubmit" />
  <invite-form ref="inviteFormRef" />
  <addAudit :open="addAuditShow" @confirm="addAuditShow = false" />
  <bulkImport :open="bulkImportShow" @confirm="bulkImportShow = false" @cancel="bulkImportShow = false" />
</template>

<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue'
  import { computed, createVNode, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import WarnIcon from '@/components/icon/IconWarning/index.vue'
  import useList from '@/hooks/use-list'
  import { studentsManageApi } from '@/services/api'

  import StaffConstitute from '../components/StaffConstitute.vue'
  import addAudit from './components/addAudit.vue'
  import bulkImport from './components/bulkImport.vue'
  import InviteForm from './components/InviteForm.vue'
  import StudentsForm from './components/StudentsForm.vue'

  const batchDisposeVisible = ref(false)
  const studentsFormRef = ref<InstanceType<typeof StudentsForm>>()
  const inviteFormRef = ref<InstanceType<typeof InviteForm>>()
  const selectedKeys = ref<string[] | number[]>(['1'])

  const rowSelection = ref({
    checkStrictly: false,
    selectedRowKeys: [] as (string | number)[],
    onChange: (selectedRowKeys: (string | number)[]) => {
      rowSelection.value.selectedRowKeys = selectedRowKeys
    }
  })

  const columns = [
    {
      title: '姓名',
      dataIndex: 'username',
      width: 200
    },
    {
      title: '学号',
      dataIndex: 'number',
      width: 200
    },
    {
      title: '手机号码',
      dataIndex: 'tel',
      width: 200
    },
    {
      title: '所属班级',
      dataIndex: 'fullOrgName',
      width: 200
    }
  ]

  const actionOption = {
    more: [
      {
        text: '编辑',
        auth: 'admin-students-and-classes-manage',
        onClick: (r: any) => openUpdateTeacherForm(r)
      },
      {
        text: '重置密码',
        auth: 'admin-students-and-classes-reset',
        onClick: (r: any) => handleResetPassword(r)
      },
      {
        text: '删除',
        auth: 'admin-students-and-classes-manage',
        onClick: (r: any) => handleDelete(r)
      }
    ]
  }

  const { pageForm, loading, dataList, getDataList } = useList<any, any>(
    studentsManageApi.list,
    {
      columns: '',
      limit: 10,
      orgId: '',
      name: '',
      offset: 1,
      order: '',
      total: 0
    },
    {
      afterCallback: () => {
        rowSelection.value.selectedRowKeys = []
      }
    }
  )
  getDataList()

  const refresh = () => {
    getDataList()
    batchDisposeVisible.value = false
    rowSelection.value.selectedRowKeys = []
  }

  //全局Loading
  const globalLoading = computed(() => {
    return loading.value
  })

  const treeSelect = (selectedKeys: any[]) => {
    getDataList({
      offset: 1,
      orgId: selectedKeys[0]
    })
  }

  const openStudentsForm = () => {
    studentsFormRef.value?.open('新建学生')
  }

  const openUpdateTeacherForm = async (r: any) => {
    const { data } = await studentsManageApi.getDetailById({}, { urlParams: { id: r.id } })
    const params = {
      id: data.id,
      number: data.number,
      tel: data.tel,
      username: data.username,
      orgId: data.orgId
    }
    studentsFormRef.value?.open('编辑学生', params)
  }

  const { runAsync: runAdd } = useRequest(studentsManageApi.add)
  const { runAsync: runUpdate } = useRequest(studentsManageApi.update)
  const studentsFormSubmit = async (state: any) => {
    studentsFormRef.value?.changeConfirmLoading(true)
    try {
      const isUpdate = studentsFormRef.value?.modalTitle === '编辑学生'
      console.log(state, 'state')

      if (isUpdate) {
        await runUpdate(state, { isAddUid: true })
      } else {
        await runAdd(state, { isAddUid: true })
      }
      refresh()
      message.success('操作成功')
      studentsFormRef.value?.close()
    } catch (error) {
      console.log(error)
    } finally {
      studentsFormRef.value?.changeConfirmLoading(false)
    }
  }

  const openInviteModal = () => {
    inviteFormRef.value?.open('邀请')
  }

  // 加入审核
  const addAuditShow = ref<boolean>(false)
  const openJoinAuditModal = () => {
    addAuditShow.value = true
  }

  // 批量导入
  const bulkImportShow = ref<boolean>(false)
  const openImportModal = () => {
    bulkImportShow.value = true
  }

  const handleResetPassword = (r: any) => {
    console.log('重置密码', r)
    Modal.confirm({
      title: '确认重置密码？',
      content: '密码将被重置为“12345678”，重置后首次登录将为要求用户重新设置新密码。',
      centered: true,
      icon: createVNode(WarnIcon),
      async onOk() {
        await studentsManageApi.resetPws({}, { urlParams: { id: r.id } })
        message.success('操作成功')
      },
      onCancel() {
        console.log('取消')
      }
    })
  }

  const handleDelete = (r: any) => {
    console.log('删除', r)
    const content = createVNode('div', null, [
      createVNode('span', null, '教师被删除后将无法登录系统'),
      createVNode('span', { style: 'color:rgba(17, 22, 31, 0.52);font-size: 12px;' }, '（教学活动数据将保留）'),
      createVNode('span', null, '，请确认操作')
    ])
    Modal.confirm({
      title: '确认删除？',
      content,
      centered: true,
      icon: createVNode(WarnIcon),
      async onOk() {
        await studentsManageApi.del({}, { urlParams: { id: r.id } })
        refresh()
        message.success('操作成功')
      },
      onCancel() {
        console.log('取消')
      }
    })
  }

  // 批量删除
  const { loading: batchDeleteLoading, runAsync: runDelList } = useRequest(studentsManageApi.delList)
  const batchDeletionOfIDs = async () => {
    await runDelList({}, { data: rowSelection.value.selectedRowKeys })
    refresh()
    message.success('操作成功')
  }
</script>

<style lang="less" scoped>
  .content-wrap {
    display: flex;
    width: 100%;
    min-height: 0;
    border-radius: 8px;
    flex: 1;
    flex-shrink: 0;
    gap: 0 16px;

    .table-wrap {
      flex: 1;
    }
  }
</style>
